import { Injectable } from '@angular/core';
import {StorageService} from './storage.service';
import {HttpClient} from '@angular/common/http';
import {HostService} from "./host.service";


@Injectable({
  providedIn: 'root'
})
export class AuthService {


  public AUTHCENTER_SERVER = this.host.HOST + "/authcenter/";

  constructor(private host: HostService,
              private http: HttpClient
    , private storage: StorageService) {


  }

  private manageloginurl = this.AUTHCENTER_SERVER + "public/login";

  login(username: string, pass: string) {
    let parm = {
      "name": username,
      "pass": pass
    }
    return this.http.post(this.manageloginurl, parm).toPromise();
  }

  getTOken() {
    return this.storage.get('TOKEN');
  }


  private refreshTokenUrl = this.AUTHCENTER_SERVER + "auth/refreshToken";

  refreshToken() {
    let last: number = 0;
    let current: number = new Date().getTime();
    this.storage.get("FRESHTIME")
      .then((value: number) => {
        // console.log("currenttime"+current);
        //  console.log("lastfreshtime"+value);
        if (current - value > (10 * 60 * 1000)) {
          this.http.get(this.refreshTokenUrl).toPromise()
            .then((data: any) => {
              if (data.token != 'error') {
                this.storage.set("TOKEN", data.token)
                  .then(() => {
                    console.log("令牌成功刷新");
                  })

                this.storage.set("FRESHTIME", current);
              }
            })
        }
      })


  }

  private getMenuListUrl=this.AUTHCENTER_SERVER+"member/getMenulist";
  getMenuList(){
    return this.http.get(this.getMenuListUrl).toPromise();
  }

  private getMemberListByRoleURL = this.AUTHCENTER_SERVER+"member/getMemberListByRole";
  getMemberListByRole(id:string){
    let parm = {
      "parm":id
    }
    return this.http.post(this.getMemberListByRoleURL,parm).toPromise()
  }

}
